package cc.co.cutenimy.nimyexplore.rcp.views;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;

import cc.co.cutenimy.nimyexplore.model.jdbc.ConnectionInstance;
import cc.co.cutenimy.nimyexplore.rcp.ApplicationContext;
import cc.co.cutenimy.nimyexplore.ui.grid.GridWidget;
import cc.co.cutenimy.nimyexplore.ui.provider.ImageTextLabelProvier;
import cc.co.cutenimy.nimyexplore.ui.provider.UniversalTreeContentProvier;

/**
 * Display the connection instances.
 * 
 * @author 234aini@gmail.com
 * 
 */
public class ConnectionsView extends ViewPart implements PropertyChangeListener {
	public static final String ID = "cc.co.cutenimy.nimyexplore.rcp.views.ConnectionsView";
	private TreeViewer viewer;

	@Override
	public void createPartControl(Composite parent) {
		viewer = GridWidget.createTreeViewer(parent);
		viewer.setContentProvider(new UniversalTreeContentProvier());
		viewer.setLabelProvider(new ImageTextLabelProvier() {

			public String getText(Object element) {
				if (element == null) {
					return null;
				}
				final ConnectionInstance instance = (ConnectionInstance) element;
				return labelFor(instance);
			}

		});
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				handleDoubleClick(event);
			}
		});

		setupTreeInput();
		ApplicationContext.get().addPropertyChangeListener(this);
	}

	protected void handleDoubleClick(final DoubleClickEvent event) {
		// TODO Auto-generated method stub
	}

	// TODO
	private String labelFor(final ConnectionInstance instance) {
		return instance.getAlias() + "(" + instance.getUrl() + ")";
	}

	private void setupTreeInput() {
		viewer.setInput(ApplicationContext.get().listConnectionInstances());
	}

	@Override
	public void setFocus() {
		viewer.getTree().setFocus();
	}

	public void propertyChange(PropertyChangeEvent evt) {
		boolean changed = evt.getPropertyName().equals(
				ApplicationContext.CONNECTION_INSTANCE_ADDED)
				|| evt.getPropertyName().equals(
						ApplicationContext.CONNECTION_INSTANCE_REMOVED);
		if (changed) {
			viewer.refresh(true);
		}
	}

}
